<template>
    <view class='bargain'>
		
	<view class='iconfont icon-xiangzuo' v-if='retunTop' @tap='goBack' :style="'top:'+navH/2+'rpx'"></view>
    <view :class="bargainUid != userInfo.uid ? 'header on' : 'header'" >
		
		<!-- {{bargainCount.lookCount}}人查看 丨 {{bargainCount.shareCount}}人分享 丨 -->
    <view class='people' :style="'top:'+navH/2+'rpx'"> {{data.detail.userCount}}人参与</view>
       <!-- <view class='time font-color' v-if="bargainUid == data.userInfo.user_id">
          倒计时 <text>{{countDownDay}}</text> 天
          <text>{{countDownHour}}</text> 时
          <text>{{countDownMinute}}</text> 分
          <text>{{countDownSecond}}</text> 秒
        </view> -->
        <view v-if="bargainUid != data.userInfo.user_id " class='pictxt acea-row row-center-wrapper'>
            <view class='pictrue'><image :src='bargainUserInfo.avatar'></image></view>
            <view class='text'>{{bargainUserInfo.nickname}}<text>邀请您帮忙砍价</text></view>
        </view>
    </view>
   <view class='wrapper'>
      <view class='pictxt acea-row row-between-wrapper' @tap="goProduct">
         <view class='pictrue'>
            <image :src='data.detail.cover_image'></image>
            <!-- <view class="bargain_view">
               查看商品
               <text class="iconfont icon-jiantou iconfonts"></text>
            </view> -->
         </view>
         <view class='text acea-row row-column-around'>
            <view class='line2'>{{data.detail.name}}</view>
			 <view class='line2'>{{data.detail.norms_value_name}}</view>
			
            <view class='money font-color'>当前: ￥<text class='num'>{{data.detail.count_price}}</text></view>
            <view class='successNum'>已有{{data.detail.pay_count || 0}}人砍价成功</view>
         </view>
      </view>
	  <view class="wrapper-djs">
		  <view class=' ' v-if="bargainUid == data.userInfo.user_id">
		    还剩 <text class="day">{{countDownDay}}</text> 天   &nbsp;
		    <text>{{countDownHour}}</text> :
		    <text>{{countDownMinute}}</text> :
		    <text>{{countDownSecond}}</text> 砍价结束
		  </view>
		  <view class="bargian-num">
			  已有<text class="day">1</text>位好友砍价成功
		  </view>
	  </view>
      <view class="cu-progress acea-row row-middle round margin-top">
        <view class='acea-row row-middle bg-red' :style="'width:'+bargainUserHelpInfo.pricePercent+'%;'"></view>
      </view>
      <view class='money acea-row row-between-wrapper'>
         <view>已砍{{data.detail.bargain_price}}元</view>
         <view>最低价{{data.detail.min_price}}元</view>
      </view>
      <!-- 自己砍价 -->
		<view v-if="bargainUid == data.userInfo.user_id && !userBargainStatus ">
			<view class='bargainBnt' @tap.stop='userBargain' v-if="data.detail.number>0">立即参与砍价</view>
			<!-- 无库存 -->
			<view class='bargainBnt grey' v-if="data.detail.number<=0">立即参与砍价</view>
		</view>
		<!-- 帮助砍价、帮砍成功：-->
		<view v-if="bargainUid == data.userInfo.user_id && data.detail.number > 0 && userBargainStatus && data.detail.bargainEstate ==0">
			 <!-- open-type='share' -->
			 <button  open-type='share' class='tipBnt bargainBnt' @click="shareUser">邀请好友帮砍价</button>
			<!-- <view class='bargainBnt' @tap='getBargainUserBargainPricePoster'>邀请好友帮砍价</view> -->
		</view>
		<view v-if="bargainUid != data.userInfo.user_id && !data.detail.bargainHelp">
			<view class='bargainBnt' @tap='setBargainHelp'>帮好友砍一刀</view>
		</view>
		<view v-if="bargainUid != data.userInfo.user_id && data.detail.bargainHelp">
			<view class='bargainSuccess'><text class='iconfont icon-xiaolian'></text>已成功帮助好友砍价</view>
			<view class='bargainBnt' @tap='currentBargainUser'>我也要参与</view>
		</view>
		<!-- 支付自定义规则 -->
		<view v-if="  bargainUid == data.userInfo.user_id && data.detail.bargainEstate == 1">
			<view class='bargainBnt' @tap='goPay'>立即支付</view>
		</view>
      <view class='bargainBnt on' @tap='goBargainList'>抢更多商品</view>
      <view class='tip'>已有<text class='font-color'>{{data.detail.pay_count}}</text> 位好友成功砍价</view>
      <view class='lock'></view>
   </view>
   <view class='bargainGang'>
      <view class='title font-color acea-row row-center-wrapper'>
         <view class='pictrue'><image :src="OSS_HOST+'img/kanjia_ico.png'"></image></view>
         <view class='titleCon'>砍价帮</view>
         <view class='pictrue on'><image :src="OSS_HOST+'img/kanjia_ico.png'"></image></view>
      </view>
      <view class='list '>
        <block v-for="item in data.log" >
          <view class='item acea-row  row-between-wrapper'>
             <view class='pictxt acea-row row-between-wrapper' style="    align-items: center;justify-content: space-between;">
                <view class='pictrue'><image :src='item.bargain_user_image||item.avatar'></image></view>
                <view class='text'>
                   <view class='name line1'>{{item.nickname}}</view>
                   <view class='line1'>{{item.bargain_time}}</view>
                </view>
             </view>
             <view class='money font-color'><text class="iconfont icon-kanjia"></text>砍掉{{item.price}}元</view>
          </view>
        </block>
      </view>
      <!-- <view class='load font-color' v-if="!limitStatus" @tap='getBargainUser'>点击加载更多</view> -->
      <view class='lock'></view>
   </view>
   <view class='goodsDetails'>
      <view class='title font-color acea-row row-center-wrapper'>
         <view class='pictrue'><image :src="OSS_HOST+'img/kanjia_ico.png'"></image></view>
         <view class='titleCon'>砍价规则</view>
         <view class='pictrue on'><image :src="OSS_HOST+'img/kanjia_ico.png'"></image></view>
      </view>
      <view class='conter'>
   		  <rich-text type="text mod" decode="true" :nodes="rule" style="line-height: 25px;">
   		  	
   		  </rich-text>
          <!-- <template  :data="data.detail.rule"/> -->
      </view>
	  <view class='lock'></view>
   </view>
   <view class='goodsDetails'>
      <view class='title font-color acea-row row-center-wrapper'>
         <view class='pictrue'><image :src="OSS_HOST+'img/kanjia_ico.png'"></image></view>
         <view class='titleCon'>商品详情</view>
         <view class='pictrue on'><image :src="OSS_HOST+'img/kanjia_ico.png'"></image></view>
      </view>
      <view class='conter'>
		  <rich-text type="text mod" decode="true" :nodes="data.detail.description" style="line-height: 25px;">
		  	
		  </rich-text>
          <!-- <template   :data="data.detail.description"/> -->
      </view>
      <!-- <view class='lock'></view> -->
   </view>
   
   <view :class=' active==true?"bargainTip on":"bargainTip"'>
       <view class='pictrue'><image :src="OSS_HOST+'img/kanjia.jpg'"></image></view>
       <view v-if="bargainUid == data.userInfo.user_id">
        <view class='cutOff'>您已砍掉<text class='font-color'>{{data.detail.bargain_price}}</text>元，听说分享次数越多砍价成功的机会越大哦！</view>
			 <button open-type='share' class='tipBnt'>邀请好友帮砍价</button>
			<!-- <button  class='tipBnt' @tap.stop="getBargainUserBargainPricePoster">邀请好友帮砍价</button> -->
       </view>
       <view v-else>
        <view class='help font-color'>成功帮砍</view><!-- {{bargainUserBargainPrice.price}}元 -->
        <view class='cutOff on'>您也可以砍价低价拿哦，快去挑选心仪的商品吧~</view>
        <view @tap='currentBargainUser' class='tipBnt'>我也要参与</view>
       </view>
	   <view class="close" @tap='close'>
	   	x
	   </view>	
   </view>
   <view class='mask' catchtouchmove="true" :hidden='active==false' @tap='close'></view>
	<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom" />
</view>
	
<!-- <authorize bind:onLoadFun="onLoadFun"></authorize>
<import src="/wxParse/wxParse.wxml"/> -->
</template>

<script>
    //公共api接口封装方法
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import {oss_host} from '@/config/config.js';
    //获取网络状态
    import {
        mapGetters
    } from 'vuex';
    export default {
        data() {
            return {
				OSS_HOST:oss_host,
                countDownDay: '00',
                countDownHour: '00',
                countDownMinute: '00',
                countDownSecond: '00',
                active: false,
                id:0,//砍价产品编号
                userInfo:{
					
				},//当前用户信息
				data:{
					detail:{},//砍价产品
					log:[],
					users:[],
					// userInfo:{},
				},
                bargainUid: 0,//开启砍价用户
				
				
                bargainUserInfo: {},//开启砍价用户信息
                // bargainUserId: 0,//开启砍价编号
                // bargainInfo:[],//砍价产品
                offset:0,
                limit:20,
                limitStatus:false,
                // bargainUserHelpList:[],
                // bargainUserHelpInfo:[],
                // bargainUserBargainPrice:0,
                status:'', // 0 开启砍价   1  朋友帮忙砍价  2 朋友帮忙砍价成功 3 完成砍价  4 砍价失败 5已创建订单
                // bargainCount:[],//分享人数  浏览人数 参与人数
                retunTop:true,
                // bargainPartake:0,
                isHelp:false,
                interval:null,
                userBargainStatus:false,//判断自己是否砍价
                productStock:0,//判断是否售罄；
                quota:0,//判断是否已限量；
                userBargainStatusHelp:true,
                navH: '',
                statusPay:'',
				rule:'',
            };
        },
        components: {
			uniPopup
        },
		
        computed: {
            //注册网络状态
            ...mapGetters(['netWorkType',,'loginStatus'])
        },
       
         /**
           * 生命周期函数--监听页面加载
           */
        onLoad(e) {
			// console.log(e)
			 var that = this;
			//  if (typeof e.bargain_id != 'undefined'){
			// 	that.bargain_id = e.bargain_id
			// }
			// e.bargainUid = ''
            // var pages = getCurrentPages();
            // if (pages.length <= 1) that.retunTop=false;
            //扫码携带参数处理
            if (e.scene) {
				let scene = decodeURIComponent(e.scene)
				
				e.bargain_id = this.getQueryVariable('bargainId', scene)
				e.bargainUid = this.getQueryVariable('bargainUid', scene)
				
				// uni.setStorageSync({
				//   key:"pid",
				//   data:e.bargainUid
				// })
             
            }
			
			             
			this.id = e.bargain_id
			
			this.bargainUid = e.bargainUid||0
			// console.log('******砍价用户bargainUid：',this.bargainUid)

           
          },
          /**
           * 生命周期函数--监听页面显示
           */
          onShow: function () {
			  
				
			  this.getBargainDetails()
          },

          /**
           * 生命周期函数--监听页面隐藏
           */
          onHide: function () {
            if (this.data.interval !== null) clearInterval(this.data.interval);
          },

          /**
           * 生命周期函数--监听页面卸载
           */
          onUnload: function () {
            if (this.data.interval !== null) clearInterval(this.data.interval);
          },

        methods: {
            // 刷新的方法
            refresh() {
                this.getBargainDetails()
            },
             goBack(){
                uni.navigateBack({ delta: 1 })
              },
			  // 分享
			shareUser(){
				// console.log(1111111)
				let _this = this
				
				// 转发私密消息
				// uni.updateShareMenu({
				//   isPrivateMessage: true,
				//   activityId: 'xxx',
				//   templateInfo: {
				// 	  'id':_this.userInfo.id
				//   },
				//   success () { 
				// 	  console.log('ssssss')
				//   },
				//   fail () {
				// 	  console.log('ffff')
				//   }
				// })

				// uni.showShareMenu({
				//   withShareTicket: true,
				//   menus: ['shareAppMessage', 'shareTimeline']
				// })
			},
			
            
           //  /**
           //     * 跳转到商品页面
           //     */
           //    goProduct(){
           //      return app.Tips('/pages/goods_details/index?id=' + this.data.bargainInfo.product_id);
           //    },
    //           goBack() {
				// uni.navigateBack({ delta: 1 })
    //           },
              gobargainUserInfo(){//获取开启砍价用户信息
                var that = this;
                var data = { bargainId: that.data.id, bargainUserUid: that.data.bargainUid };
                // postBargainStartUser(data).then(res=>{
                //   that.setData({ bargainUserInfo: res.data });
                // });
              },
              goPay() {//立即支付
				let _this = this 
					_this.$refer.setVilit('/pages/PayOrder/submit_order')
					let callback = function(url) {
						_this.$refs.popupvLogin.open()
					}
					let product = [
						{
							id:this.data.detail.product_id,//产品id
							norms_value_id:this.data.detail.norms_value_id,
							num:1,
							bargainId:this.data.detail.id,//砍价id
						},
					]
					
					// 结合购物车多产品的情况
					let data = {
						product:JSON.stringify(product)
						
						
					}
					uni.setStorageSync('param',JSON.stringify(data))
					_this.$refer.toUrl(callback, data)
              },
              getBargainDetails(){//获取砍价产品详情
               const _this = this
               //console.log(66)
			   let data = {
				   id:_this.id,
				   bargainUid:_this.bargainUid
			   }
               var opt = {
                   url: '/bargain/bargainDetail',
				   data:data,
                   success: function(res) {
                       //console.log(res)
						let result = res.data
                       if (res.status == 1) {
                           _this.data.detail= result.detail
						   _this.data.log = result.log
						   _this.data.users= result.users
						   _this.data.userInfo = result.userInfo
						   _this.rule=result.rule
						   _this.data.detail.description = _this.data.detail.description.replace(/\<img/gi,
						   	'<img style="max-width:100%;height:auto;display:block;margin:0 auto;" ').replace(/&nbsp;/g, '\xa0')
						   _this.data.detail.rule = _this.data.detail.rule.replace(/\<img/gi,
						   	'<img style="max-width:100%;height:auto;display:block;margin:0 auto;" ').replace(/&nbsp;/g, '\xa0')
						  
						   // _this.active = result.detail.userBargainStatus
						   if(!_this.bargainUid && _this.loginStatus){
							   
							   _this.bargainUid = _this.data.userInfo.user_id
						   }
						   _this.userBargainStatus = _this.data.detail.userBargainStatus
						    _this.time2( _this.data.detail.end_time,_this);
						   // console.log('******s',_this.data.detail.userBargainStatus)
                       } else {
                           uni.showToast({
                               icon: 'none',
                               title: res.message
                           });
                       }
               
                   }
               };
               _this.$service.GetApi(opt)
             
              },
              // 自己砍价；
              userBargain(){
                this.bargainUid = this.data.userInfo.user_id
                if(!this.loginStatus){
                	this.$refs.popupvLogin.open()
                }
                this.setBargainHelp();
              },
              
              currentBargainUser(){//当前用户砍价
				this.bargainUid = this.data.userInfo.user_id
				if(!this.loginStatus){
					this.$refs.popupvLogin.open()
				}
                this.setBargainHelp();
              },
              setBargain(){//参与砍价
				   this.bargainUid = this.data.userInfo.user_id
				   if(!this.loginStatus){
					this.$refs.popupvLogin.open()
				   }
				   this.setBargainHelp();
              },
              setBargainHelp() {//帮好友砍价
                var that = this;
				if(!that.loginStatus){
					that.$refs.popupvLogin.open()
					return 
				}
                var data = { 
					bargain_product_id: that.data.detail.id, 
					user_id: that.bargainUid , //参与砍价用户id 自己，好友
				};				
				
				var opt = {
				    url: '/bargain/help',
					data:data,
				    success: function(res) {
				        //console.log(res)
						let result = res.data
				        if (res.status == 1) {
				            that.getBargainDetails()
							
				            uni.showToast({
				                icon: 'none',
				                title: '砍价成功'
				            });
				        } else {
				            uni.showToast({
				                icon: 'none',
				                title: res.message
				            });
				        }
				
				    }
				};
				that.$service.GetApi(opt)
               
              },
			  
              getBargainUserBargainPricePoster(){
				  const _this = this
				  
				  _this.$refer.setVilit('/pages/BargainDetails/qrcode/qrcode')
				  let callback = function(url) {
				      _this.$refs.popupvLogin.open()
				  }
				  var data = {
				      id: this.data.detail.id
				  }
				  _this.$refer.toUrl(callback, data)
				// this.active=true 
				  //分享图片
               
                
              },
			  //获取帮忙砍价砍掉多少金额
              getBargainUserBargainPrice(){
				  
                var that = this;
                var data = {bargainId: that.data.id,bargainUserUid: that.data.bargainUid};
     //            postBargainHelpPrice(data).then(res=>{
     //              that.setData({ bargainUserBargainPrice: res.data, active: true });
     //            }).catch(err=>{
					
     //              that.setData({ active: false });
     //            });
              },
              goBargainList(){//跳转
                 uni.navigateTo({
                   url: '/pages/Bargain/index',
                 })
              },
              close(){
				  this.active =false
                
              },
			  
			  // 时分秒
			  time(timeStamp,that) {
			    var interval = null,totalSecond = timeStamp - Date.parse(new Date()) / 1000;
			    interval = setInterval(function () {
			      // 秒数  
			      var second = totalSecond;
			  
			      // 小时位  
			      var hr = Math.floor(second / 3600);
			      var hrStr = hr.toString();
			      if (hrStr.length == 1) hrStr = '0' + hrStr;
			  
			      // 分钟位  
			      var min = Math.floor((second - hr * 3600) / 60);
			      var minStr = min.toString();
			      if (minStr.length == 1) minStr = '0' + minStr;
			  
			      // 秒位  
			      var sec = second - hr * 3600 - min * 60;
			      var secStr = sec.toString();
			      if (secStr.length == 1) secStr = '0' + secStr;
			     
			        this.countDownHour= hrStr,
			        this.countDownMinute= minStr,
			        this.countDownSecond= secStr,
			      
			      totalSecond--;
			      if (totalSecond <= 0) {
			        clearInterval(interval);
			        uni.showToast({
			          title: '活动已结束',
			          icon: 'none',
			          duration: 1000,
			          mask: true,
			        })
			       
					this.countDownHour= '00'
			        this.countDownMinute= '00'
			        this.countDownSecond= '00'
			        
			      }
			    }.bind(this), 1000);
			    this.interval=interval;
			  },
			  // 天 时分秒
			  time2(timeStamp, that) {
			    var totalSecond = timeStamp - Date.parse(new Date()) / 1000;
			    var interval = setInterval(function () {
			      // 秒数  
			      var second = totalSecond;
			      // // 天数位  
			      var day = Math.floor(second / 3600 / 24);
			      var dayStr = day.toString();
			      if (dayStr.length == 1) dayStr = '0' + dayStr;
			      // 小时位  
			      var hr = Math.floor((second - day * 3600 * 24) / (60 * 60));
			      var hrStr = hr.toString();
			      if (hrStr.length == 1) hrStr = '0' + hrStr;
			  
			      // 分钟位  
			      // var min = Math.floor((second - hr * 3600) / 60);
			      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
			      var minStr = min.toString();
			      if (minStr.length == 1) minStr = '0' + minStr;
			  
			      // 秒位  
			      // var sec = second - hrNew * 3600 - min * 60;
			      var sec = Math.floor(second - day * 3600 * 24 - hr * 3600 - min * 60);
			      var secStr = sec.toString();
			      if (secStr.length == 1) secStr = '0' + secStr;
			  
			      
			        this.countDownDay= dayStr
			        this.countDownHour= hrStr
			        this.countDownMinute= minStr
			        this.countDownSecond= secStr
			      
			      totalSecond--;
			      if (totalSecond <= 0) {
			        clearInterval(interval);
			        uni.showToast({
			          title: '活动已结束',
			        });
			        
			          this.countDownDay= '00'
			          this.countDownHour= '00'
			          this.countDownMinute= '00'
			          this.countDownSecond= '00'
			        
			      }
			    }.bind(that), 1000);
			    this.interval= interval;
			  },
			  
			  //解析url参数
			  /*
			   *  variable   参数名
			   *  url        URL
			   */
			  getQueryVariable(variable, url) {
			  	//var url = 'https://api.aiouning.com/wechat/product/param/?sid=12&pid=37&bid=1&cid=2';
			  	var vars = url.split("param/?");
			  	// vars[1] = vars[1].replace(/%3D/g, "=").replace(/%26/g, "&")
			  	//console.log(vars)
			  	var param = vars[1].split("&");
			  	for (var i = 0; i < param.length; i++) {
			  		var pair = param[i].split("=");
			  		//console.log(pair)
			  		if (pair[0] == variable) {
			  			return pair[1];
			  		}
			  	}
			  	return (false);
			  },
        }
    }
</script>

<style lang="scss">
    @import "./index.scss";
</style>
